import json
import random
import time

from apscheduler.schedulers.background import BackgroundScheduler

from ..center.send import MQSendMessage
from ...myredis.myredisclient import getDataFromRedis


class SendMQUse(MQSendMessage):
    def __init__(self, cofig, queuetest):
        super(SendMQUse, self).__init__(cofig, queuetest)
        self.config = cofig
        self.ProxyPool = []
        self.TaskPool = []
        self.Scheduler = BackgroundScheduler()
        self.InitTimer()

    def UpdateProxyPool(self):
        self.ProxyPool = list(getDataFromRedis(self.config))
        print('Update ProxyPool size: %d' % len(self.ProxyPool))
        print('current time:' + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))


    # 添加并启动定时任务
    def InitTimer(self):
        # http://blog.itpub.net/26250550/viewspace-2130398
        self.Scheduler.add_job(self.UpdateProxyPool, 'interval', minutes=1)  # 刷新代理池
        self.Scheduler.start()

    def UpdateTaskPool(self):
        """
        將此处结果加入到 self.TaskPool
        :return:
        """
        pass


    def run(self):
        while True:
            while True:
                print('ProxyPool  have proxy size: %d' % len(self.ProxyPool))
                if len(self.ProxyPool) < 10:
                    print('Proxy pool too small, reject task! %s' % time.strftime('%H:%M:%S', time.localtime()))
                    # time.sleep(1)
                    self.ConnRabbitMQ.sleep(1)
                else:
                    # proxy = choice(self.ProxyPool) # 随机取一个
                    proxys = random.sample(self.ProxyPool, 5)
                    print("get proxys random sample 5: %s" % str(proxys))
                    break
            while True:
                # 这里必须重新获取队列 否则下面队列得到的数值始终不变
                self.set_queue_declare(passive=True)
                # 获取服务器消息队列的量
                ready = self.get_message_count()
                # 取整除 - 返回商的整数部分（向下取整）
                threshold = len(self.TaskPool) // 10
                # 任务池任务小于100 时
                if threshold < 10:
                    threshold += 10
                # 任务池任务大于1000时
                elif threshold > 100:
                    threshold = 100
                if ready < threshold:
                    break
                    # time.sleep(1)
                self.ConnRabbitMQ.sleep(1)

            if not self.TaskPool:  # 如果任务池为空，尝试刷新
                self.UpdateTaskPool()

            if not self.TaskPool:  # 空如果刷新后任务池还为
                print('TaskQueue empty!')
                # time.sleep(1)
                self.ConnRabbitMQ.sleep(1)
                continue

            dic = self.TaskPool.pop()
            dic['proxy'] = proxys
            task = json.dumps(dic, ensure_ascii=False).encode('utf-8')
            self.publish(task)
            print('send message: %s' % task)
            print('Message ready: %d, TaskPool size: %d, threshold: %d, %s'
                  % (ready, len(self.TaskPool), threshold, time.strftime('%H:%M:%S', time.localtime())))




#
# if __name__ == "__main__":
#     UpdateProxyPool()
#     InitTimer()
#     MQQueueCenter2Node = GolobalConfig['get_article']['MQQueueCenter2Node']
#     mqsend = MQSendMessage("./config/config.ini", "queuetest")
#     mqsend.setQueue(MQQueueCenter2Node)
#     mqsend.set_queue_declare(passive=True)
#     while True:
#         while True:
#             print('ProxyPool size: %d' % len(ProxyPool))
#
#             if len(ProxyPool) < 10:
#                 print('Proxy pool too small, reject task! %s' % time.strftime('%H:%M:%S', time.localtime()))
#                 # time.sleep(1)
#                 mqsend.ConnRabbitMQ.sleep(1)
#             else:
#                 proxy = choice(ProxyPool)
#                 break
#         while True:
#             ready = mqsend.get_message_count()
#             # 取整除 - 返回商的整数部分（向下取整）
#             threshold = len(TaskPool) // 10
#             if threshold < 10:
#                 threshold += 10
#             elif threshold > 100:
#                 threshold = 100
#             print('Message ready: %d, TaskPool size: %d, threshold: %d, %s'
#                   % (ready, len(TaskPool), threshold, time.strftime('%H:%M:%S', time.localtime())))
#             if ready < threshold:
#                 break
#                 # time.sleep(1)
#             mqsend.ConnRabbitMQ.sleep(1)
#
#         if not TaskPool:  # 如果任务池为空，尝试刷新
#             UpdateTaskPool()
#
#         if not TaskPool:  # 如果刷新后任务池还为空
#             print('TaskQueue empty!')
#             # time.sleep(1)
#             ConnRabbitMQ.sleep(1)
#             continue
